package com.beiding.jsonanalyzer.querylink;

import com.alibaba.fastjson.JSONObject;
import com.beiding.jsonanalyzer.Analyzer;
import com.beiding.jsonanalyzer.Key;
import com.beiding.jsonanalyzer.flow.ValueNode;
import com.beiding.jsonanalyzer.flow.BranchNode;
import com.beiding.jsonanalyzer.flow.flowevents.DataNodeEvent;

public class NamedAsQueryLinkNode<W extends ValueNode> extends ComputeNode<W> {

    private Object key;

    public NamedAsQueryLinkNode(QueryLinkNode<W> preNode, Object key) {
        super(preNode);
        this.key = key;
    }


    @Override
    protected void bindByComputeNode(BranchNode<W> preResult, BranchNode<W> newBranchNode) {


        ComputeNodeUtils.bindControlEvent(preResult, newBranchNode);

        preResult.onDataEvent(DataNodeEvent.eventType(), event -> {

            W dataNode = event.getData();
            W w = newBranchNode.getBranch().getValueNodeFactory().create();
            JSONObject jsonObject = new JSONObject();
            if (key instanceof Key) {
                Analyzer.set(jsonObject, key, dataNode.get());
            } else if (key instanceof String) {
                jsonObject.put((String) key, dataNode.get());
            }
            w.set(jsonObject);
            newBranchNode.signDataEvent(new DataNodeEvent<>(w));

        });
    }
}
